package com.chuan.icons;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class Account extends ListActivity implements OnItemClickListener,
		OnItemLongClickListener {
	public static final int RET_ACCOUNT_SUCCESS = 1;
	private Menu mMenu;
	private ListAdapter mListAdapter = null;
	private ArrayList<HashMap<String, String>> mAcccounts = new ArrayList<HashMap<String, String>>();

	protected static final int DB_DONE = 0x102;
	protected static final int WAIT_DIALOG = 0x1001;
	protected static final int PAIRED_DIALOG = 0x1002;
	protected static final int FETCH_DIALOG = 0x1003;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Account.DB_DONE:
				updateAccount();
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getListView().setOnItemLongClickListener(this);
		getListView().setOnItemClickListener(this);

		showDialog(WAIT_DIALOG);
		Thread thread = new Thread() {
			@Override
			public void run() {
				LiteDB.openLiteDB();
				Common.updateContacts(getApplicationContext());
				dismissDialog(WAIT_DIALOG);
				Message msg = new Message();
				msg.what = Account.DB_DONE;
				handler.sendMessage(msg);
			}
		};
		thread.start();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void updateAccount() {
		if (!getAccountList()) {
			showInfo("Get account fail.");
			finish();
			return;
		}

		mListAdapter = new SimpleAdapter(this, mAcccounts,
				android.R.layout.simple_list_item_2, new String[] { "user",
						"site" }, new int[] { android.R.id.text1,
						android.R.id.text2 });
		setListAdapter(mListAdapter);
	}

	private boolean getAccountList() {
		JSONArray accounts = LiteDB.getAccounts();
		HashMap<String, String> item = null;
		mAcccounts.clear();

		for (int n = 0; n < accounts.length(); ++n) {
			JSONObject account = null;
			try {
				account = accounts.getJSONObject(n);
			} catch (JSONException e1) {
				continue;
			}
			item = new HashMap<String, String>();
			try {
				item.put("user", account.getString("user"));
				item.put("site", account.getString("site"));
				mAcccounts.add(item);
			} catch (JSONException e) {
				continue;
			}
		}

		item = new HashMap<String, String>();
		item.put("user", getResources().getString(
				R.string.str_add_new_account_item));
		item.put("site", "");
		mAcccounts.add(item);

		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
		// If user client this, we will load new account activity.
		if (pos >= mAcccounts.size() - 1) {
			addNewAccountActivity();
			return;
		}

		final HashMap<String, String> item = mAcccounts.get(pos);

		Intent it = new Intent(Account.this, FriendsTab.class);
		it.putExtra(Constants.PARAMETER_USER, item.get("user"));
		it.putExtra(Constants.PARAMETER_SITE, item.get("site"));
		startActivity(it);
	}

	public boolean getFriendsList(String user, String type) {
		JSONObject data = new JSONObject();
		try {
			data.put("user", user);
			data.put("site", type);
		} catch (JSONException e) {
			return false;
		}

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		mMenu = menu;
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.account, mMenu);
		return true;
	}

	private void addNewAccountActivity() {
		Dialog d = newAccountTypeDialog();
		if (d != null) {
			d.show();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.AddAccount:
			addNewAccountActivity();
			return true;

		case R.id.Refresh:
			updateAccountList();
			return true;

		default:
			break;
		}

		return false;
	}

	// Create new accounts
	private void newAccount(String site) {
		Intent it = new Intent(Account.this, Parameter.class);
		it.putExtra("site", site);
		startActivityForResult(it, RET_ACCOUNT_SUCCESS);
	}

	private void deleteAccount(int position) {
		HashMap<String, String> item = mAcccounts.get(position);
		if (LiteDB.deleteAccounts(item.get("user"), item.get("site")) > 0) {
			updateAccountList();
			showInfo("Delete account success.");
		} else {
			showInfo("Delete account fail.");
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		if (position >= mAcccounts.size() - 1) {
			return false;
		}

		final int pos = position;
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setTitle("Select action:");
		b.setItems(R.array.Action, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) {
					// Delete account.
					deleteAccount(pos);
				}
			}
		});

		b.create().show();
		return true;
	}

	private void showInfo(String info) {
		Toast.makeText(this, info, Toast.LENGTH_SHORT).show();
	}

	private void updateAccountList() {
		getAccountList();
		if (mListAdapter != null) {
			((BaseAdapter) mListAdapter).notifyDataSetChanged();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RET_ACCOUNT_SUCCESS) {
			return;
		}

		if (data.getBooleanExtra("addSuccess", false)) {
			updateAccountList();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case WAIT_DIALOG: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle(R.string.str_readcontacts);
			dialog.setMessage(getResources().getText(R.string.str_wait));

			dialog.setIndeterminate(false);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	private String[] getAllSites() {
		Resources res = getResources();
		return res.getStringArray(R.array.sites);
	}

	private Dialog newAccountTypeDialog() {
		final String[] namelist = getAllSites();
		if (namelist == null) {
			return null;
		}

		AlertDialog.Builder b = new AlertDialog.Builder(this);

		b.setTitle(getResources().getString(R.string.str_select_site));
		b.setItems(namelist, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				newAccount(namelist[which]);
			}
		});

		return b.create();
	}
}
